/** @format */

import { computed, onMounted } from 'vue'
import { CACHE_KEY } from '../contants/configCont'
import { isSameBook } from '../utils/commonUtils'
import { useEntity } from './useEntity'

const { content, getData, updateData } = useEntity({
  cacheKey: CACHE_KEY.hotBooks,
  path: 'hot.json',
})

const hotBooks = computed(() => content.value?.list || [])

const checkIsExist = (book) => {
  const list = hotBooks.value
  const index = list.findIndex((item) => isSameBook(item, book))
  return index != -1
}

const addHotBook = async (book) => {
  const list = hotBooks.value
  if (!checkIsExist(book)) {
    list.push(book)
    return await updateData({ list })
  }
}

const removeHotBook = async (book) => {
  const list = hotBooks.value
  const index = list.findIndex((item) => isSameBook(item, book))
  if (index !== -1) {
    list.splice(index, 1)
    return await updateData({ list })
  }
}

const toggleHotBook = async (book) => {
  const list = hotBooks.value
  const index = list.findIndex((item) => isSameBook(item, book))
  if (index === -1) {
    list.push(book)
  } else {
    list.splice(index, 1)
  }
  return await updateData({ list })
}

export const useHotBook = (options = {}) => {
  options.mounted &&
    onMounted(() => {
      getData()
    })
  return {
    hotBooks,
    checkIsExist,
    addHotBook,
    removeHotBook,
    toggleHotBook,
  }
}
